import store from "@/store";
import { ElMessage } from "element-plus";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  // redirection
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    name: "login",
    component: () => import(/* webpackChunkName: "Home" */ "@/views/Login.vue")
  },
  // system
  {
    path: "/managesystem",
    name: "managesystem",
    redirect: "/managesystem/index",
    component: () => import(/* webpackChunkName: "Home" */ "@/views/Home.vue"),
    meta: {
      // need Token
      requireToken: true,
      title: "首页"
    },
    // children router
    children: [
      // system page, project and stream...
      {
        path: "index",
        name: "index",
        component: () =>
          import(
            /* webpackChunkName: "showprojects;" */ "@/views/ManageSystem.vue"
          ),
        meta: {
          title: "项目管理系统"
        }
      },
      // project manage system
      {
        path: "projectsystem",
        name: "projectsystem",
        component: () =>
          import(
            /* webpackChunkName: "projectsystem;" */ "@/views/SubSystem.vue"
          ),
        meta: {
          title: "立项及查询系统"
        }
      },
      // incomestream manage system
      {
        path: "incomestreamsystem",
        name: "incomestreamsystem",
        component: () =>
          import(
            /* webpackChunkName: "incomestreamsystem;" */ "@/views/SubSystem.vue"
          ),
        meta: {
          title: "培训费用收入流水系统"
        }
      },
      {
        path: "outlaystreamsystem",
        name: "outlaystreamsystem",
        component: () =>
          import(
            /* webpackChunkName: "outlaystreamsystem;" */ "@/views/SubSystem.vue"
          ),
        meta: {
          title: "培训费用支出流水系统"
        }
      },
      // authority management page
      {
        path: "/adminsystem",
        name: "adminsystem",
        component: () =>
          import(/* webpackChunkName: "adminsystem" */ "@/views/SubSystem.vue"),
        meta: {
          title: "管理员系统",
          requireAdmin: true
        }
      }
    ]
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  linkExactActiveClass: "active"
});

// router navigation defender
router.beforeEach(to => {
  // if without token
  if (to.meta.requireToken && localStorage.getItem("token") == null) {
    ElMessage("当前未登录,点击确认将跳转至登录页面..");
    return "/login";
  }
  // 防止直接改路由
  if (to.meta.requireAdmin && store.state.nowUser.userRole != "admin") {
    ElMessage.error(
      `您当前的账户:[${store.state.username}]无权限使用此功能，请联系管理员管理该账户权限`
    );
    return false;
  }
});

export default router;
